const querystring = require('querystring')
const handleBlogRouter = require('./src/router/blog')
const handleUserRouter = require('./src/router/user')

// 用于处理post data
const getPostData = req => {
    const promise = new Promise((resolve, reject) => {
        if (req.method !== 'POST') {
            resolve({})
            return
        }
        if (req.headers['content-type'] !== 'application/json') {
            resolve({})
            return
        }
        let postData = ''
        req.on('data', chunk => {
            postData += chunk.toString()
        })
        req.on('end', () => {
            if (!postData) {
                resolve({})
                return
            }
            resolve(JSON.parse(postData))
        })
    })
    return promise
}

const serverHandle = (req, res) => {
    // 设置返回格式,要设置，否则会乱码
    res.setHeader('Content-type', 'application/json')
    const url = req.url
    // 获取path
    req.path = url.split('?')[0]

    // 处理url上的参数
    req.query = querystring.parse(url.split('?')[1])

    getPostData(req).then(postData => {
        req.body = postData // 如果是post请求，此时我们会获取到客户端传过来的数据，并且这个postData肯定是要存到数据库的；如果是get请求，则为{}

        // 处理blog路由
        const blogResult = handleBlogRouter(req, res) //handleBlogRouter也是一个promise
        if (blogResult) {
            blogResult.then(blogData => {
                res.end(JSON.stringify(blogData))
            })
            return
        }

        // 处理user路由
        const userResult = handleUserRouter(req, res)
        if (userResult) {
            userResult.then(userData => {
                res.end(JSON.stringify(userData))
            })
            return
        }

        // 未命中路由，返回404
        res.writeHead(404, { 'content-type': 'text/plain' })
        res.write('404 Not Found\n')
        res.end()
    })
}

module.exports = serverHandle
